﻿using UnityEditor;
using System.IO;
using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using System.Diagnostics;
using System.Threading;

public class CreateAssetbundles
{
    private static string manifest = "manifest.json";   // 热更新文件信息

    //[MenuItem("AssetsBundle/BuildLuaToBytes")]
    //public static void BuildLuaToBytes()
    //{
    //    var luaRes = Application.dataPath + "/LuaScripts";
    //    var luaBytesPath = Application.dataPath + "/LuaBytes";
    //    if (Directory.Exists(luaBytesPath))
    //    {
    //        Directory.Delete(luaBytesPath, true);
    //    }
    //    Directory.CreateDirectory(luaBytesPath);
    //    BuildLuaToBytesInPath(luaRes);
    //    UnityEngine.Debug.Log("BuildLuaToBytes Success!");
    //}

    public static void BuildLuaToBytesInPath(string path)
    {
        var dirInfo = new DirectoryInfo(path);
        var folders = dirInfo.GetDirectories();
        var files = dirInfo.GetFiles();
        for (int i = 0; i < files.Length; ++i)
        {
            var file = files[i];
            if (file.Extension == ".lua")
            {
                var targetFileName = path.Replace("LuaScripts", "LuaBytes");
                if(!Directory.Exists(targetFileName))
                {
                    Directory.CreateDirectory(targetFileName);
                }
                UnityEngine.Debug.Log(targetFileName);
                targetFileName = targetFileName + "/" + file.Name.Replace(".lua", ".bytes"); ;
                UnityEngine.Debug.Log(targetFileName);
                //File.Delete(targetFileName);
                RunCmd("luac -o " + targetFileName + " " + file.FullName);
            }
        }
        for (int i = 0; i < folders.Length; ++i)
        {
            var folder = folders[i];
            BuildLuaToBytesInPath(folder.FullName);
        }
    }

    static void RunCmd(string cmdStr)
    {
        UnityEngine.Debug.Log(cmdStr);
        //例Process
        Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";         //确定程序名
        p.StartInfo.UseShellExecute = false;      //Shell的使用
        p.StartInfo.RedirectStandardInput = true;  //重定向输入
        p.StartInfo.RedirectStandardOutput = true; //重定向输出
        p.StartInfo.RedirectStandardError = true;  //重定向输出错误
        p.StartInfo.CreateNoWindow = false;        //设置置不显示示窗口
        p.Start();
        p.StandardInput.WriteLine(cmdStr + "&exit");
        p.StandardInput.AutoFlush = true;
        p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        p.Close();
    }

    //static void CmdThread()
    //{
    //    Thread newThread = new Thread(new ThreadStart(NewThread));
    //}

    //static 

//    static void CmdThread() { }
//Thread newThread = new Thread(new ThreadStart(NewThread));
//    newThread.Start();  }
//static void NewThread()
//｛  
//RunCmd(global_cmd);
//}

   static void ClearAssetBundlesName()
    {
        //获取所有的AssetBundle名称  
        string[] abNames = AssetDatabase.GetAllAssetBundleNames();
        //强制删除所有AssetBundle名称  
        for (int i = 0; i < abNames.Length; i++)
        {
            AssetDatabase.RemoveAssetBundleName(abNames[i], true);
        }
    }

    [MenuItem("AssetsBundle/Auto Set AssetBundleName")]
    static void AutoSetBundleName()
    {
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.0f);
        ClearAssetBundlesName();
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.3f);
        var dirRes = Application.dataPath + "/Resources/Prefabs";
        var dirScene = Application.dataPath + "/Scenes";
        var luaDire = Application.dataPath + "/LuaBytes";
        AutoSetPathBundleName(dirRes);
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.6f);
        AutoSetPathBundleName(dirScene);
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.8f);
        AutoSetPathBundleName(luaDire, true);
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.9f);
        AssetDatabase.Refresh();
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 1.0f);
        UnityEngine.Debug.Log("AutoSetBundleName Success!");
        EditorUtility.ClearProgressBar();
        //string[] files = Directory.GetFiles(dirRes);
    }

    static void AutoSetPathBundleName(string path, bool isLua = false)
    {
        var folderInfo = new DirectoryInfo(path);
        //截取Assets之后的路径
        //AssetImporter.GetAtPath必须是unity工程的相对路径
        //所以要Assets开头
        var folders = folderInfo.GetDirectories();
        var files = folderInfo.GetFiles();
        for (int i = 0; i < files.Length; ++i)
        {
            var file = files[i];
            if (file.Extension != ".meta" && file.Extension != ".code-workspace")
            {
                if (isLua)
                {
                    int index = file.FullName.IndexOf("Assets");
                    string filePath = file.FullName.Substring(index);
                    AssetImporter importer = AssetImporter.GetAtPath(filePath);
                    int indexLua = file.FullName.IndexOf("LuaBytes");
                    string filePathLua = file.FullName.Substring(indexLua);
                    //UnityEngine.Debug.Log(filePathLua);
                    var bundleName = filePathLua.Replace("\\", ".");
                    bundleName = bundleName.Replace("." + file.Name, "");
                    bundleName = bundleName + ".asset";
                    //UnityEngine.Debug.Log(file.Name);
                    //File.Move(file.FullName,)
                    //var bundleName = filePathLua.Replace("\\" + file.Name, "");
                    importer.assetBundleName = bundleName;
                }
                else
                {
                    int index = file.FullName.IndexOf("Assets");
                    string filePath = file.FullName.Substring(index);
                    AssetImporter importer = AssetImporter.GetAtPath(filePath);
                    importer.assetBundleName = folderInfo.Name;
                }

            }
        }
        for (int i = 0; i < folders.Length; ++i)
        {
            AutoSetPathBundleName(folders[i].FullName, isLua);
        }
    }

    static int CheckPathType(string path)
    {
        if(File.Exists(path))
        {
            return 1;
        }
        else if(Directory.Exists(path))
        {
            return 2;
        }
        else
        {
            return 3;
        }
    }

    [MenuItem("AssetsBundle/Build AssetBundles")]
    static void BuildAllAssetBundles()//进行打包
    {
        string dir = "AssetBundles";
        //判断该目录是否存在
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.0f);
        if (Directory.Exists(dir))
        {
            Directory.Delete(dir, true);
        }
        Directory.CreateDirectory(dir);//在工程下创建AssetBundles目录
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.4f);
        //参数一为打包到哪个路径，参数二压缩选项  参数三 平台的目标
        BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 1.0f);
        UnityEngine.Debug.Log("BuildAllAssetBundles Success!");
        EditorUtility.ClearProgressBar();
    }

    [MenuItem("AssetsBundle/Build Manifest")]
    static void BuildManifest()
    {
        string dir = "AssetBundles";
        var maniPath = Directory.GetCurrentDirectory() + "/" + manifest;
        string version = "1.0";
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.0f);
        if (File.Exists(maniPath))
        {
            var data= File.ReadAllText(maniPath);
            var temp= JsonUtility.FromJson<JsonModle>(data);
            version = temp.version + 1;
        }
        JsonModle module = new JsonModle();
        module.name = "manifest";
        module.core = 1;
        module.version = version;
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.1f);
        //判断该目录是否存在
        if (Directory.Exists(dir))
        {
            var curPath = Directory.GetCurrentDirectory();
            curPath = Path.Combine(curPath, dir);
            DirectoryInfo folder = new DirectoryInfo(curPath);
            var fileList = folder.GetFiles();//Directory.GetFiles(curPath);
            module.fileList = new string[fileList.Length];
            for(int i=0;i<fileList.Length;++i)
            {
                var file = fileList[i];
                var md5Value = GetMD5HashFromFile(file.FullName);
                var fileName = file.Name;
                module.fileList[i] = fileName + ":" + md5Value + ":" + file.Length;
            }
        }
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.9f);
        //Application.persistentDataPath;
        if (!File.Exists(maniPath))
        {
            var fileStream = File.Create(maniPath);
            fileStream.Close();
        }
        var jsonData = JsonUtility.ToJson(module);
        File.WriteAllText(maniPath, jsonData);
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 1.0f);
        UnityEngine.Debug.Log("BuildManifest Success!");
        EditorUtility.ClearProgressBar();
    }

    [MenuItem("AssetsBundle/UploadAssetToServer")]
    static void UploadAssetToServer()
    {
        string dir = "AssetBundles";
        var curPath = Directory.GetCurrentDirectory();
        curPath = Path.Combine(curPath, dir);
        DirectoryInfo folder = new DirectoryInfo(curPath);
        var fileList = folder.GetFiles();
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.0f);
        for (int i = 0; i < fileList.Length; i++)
        {
            UnityEngine.Debug.Log(fileList[i].FullName);
            UnityEngine.Debug.Log(fileList[i].Name);
            var data = File.ReadAllBytes(fileList[i].FullName);
            File.Copy(fileList[i].FullName, "E:/apache-tomcat-8.5.54-windows-x64/apache-tomcat-8.5.54/webapps/mmorpg/Assets/" + fileList[i].Name, true);
        }
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 1.0f);
        UnityEngine.Debug.Log("UploadAssetToServer Success!");
        EditorUtility.ClearProgressBar();
    }

    [MenuItem("AssetsBundle/CopyAssetsToStreamAsset")]
    static void CopyAssetsToStreamAsset()
    {
        string dir = "AssetBundles";
        var curPath = Directory.GetCurrentDirectory();
        curPath = Path.Combine(curPath, dir);
        DirectoryInfo folder = new DirectoryInfo(curPath);
        var fileList = folder.GetFiles();
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.0f);
        if (!Directory.Exists(Application.streamingAssetsPath + "/Assets"))
        {
            Directory.CreateDirectory(Application.streamingAssetsPath + "/Assets");
        }
        for (int i = 0; i < fileList.Length; i++)
        {
            UnityEngine.Debug.Log(fileList[i].FullName);
            UnityEngine.Debug.Log(fileList[i].Name);
            var data = File.ReadAllBytes(fileList[i].FullName);
            File.Copy(fileList[i].FullName, Application.streamingAssetsPath + "/Assets/" + fileList[i].Name, true);
        }
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 1.0f);
        File.Copy(Directory.GetCurrentDirectory() + "/" + manifest, Application.streamingAssetsPath + "/" + manifest, true);
        UnityEngine.Debug.Log("CopyAssetsToStreamAsset Success!");
        EditorUtility.ClearProgressBar();
    }

    [MenuItem("AssetsBundle/UploadMainifestToServer")]
    static void UploadMainifestToServer()
    {
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 0.0f);
        var curPath = Directory.GetCurrentDirectory();
        File.Copy(curPath + "/" + manifest, "E:/apache-tomcat-8.5.54-windows-x64/apache-tomcat-8.5.54/webapps/mmorpg/" + manifest, true);
        EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", 1.0f);
        UnityEngine.Debug.Log("UploadMainifestToServer Success!");
        EditorUtility.ClearProgressBar();
    }

    static string GetMD5HashFromFile(string fileName)
    {
        try
        {
            FileStream file = new FileStream(fileName, FileMode.Open);
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);
            file.Close();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
        }
    }
}